// hooks 封装逻辑，提供响应式数据。
import { useIntersectionObserver, useIntervalFn } from "@vueuse/core";
import { ref,onUnmounted  } from "vue";
import dayjs from "dayjs";
//数据懒加载
export const useLazyData = (target, apiFn) => {
  // console.log("apiFn", apiFn);
    const result = ref([])
    //stop 停止观察
    const { stop } = useIntersectionObserver(
      //target 监听的目标对象
      target,
      ([{ isIntersecting }], observerElement) => {
        //isIntersecting 是否进入可视区
        if (isIntersecting) {
          stop();
          // 调用API获取数据
          apiFn().then((data) => {
            result.value = data.result;
          });
        }
      },
      { threshold: 0 }
    );
    return result
}
// 支付倒计时
export const usePayTime = () => {
  const time = ref(null)
  const timeText = ref(null)
  const { pause, resume } = useIntervalFn(() => {
    time.value--
    timeText.value = dayjs.unix(time.value).format("mm分ss秒");
    if(time.value<=0){pause()}
  }, 1000, false);
  // 开启定时器
  const start = (countDown) => {
    time.value = countDown
    timeText.value = dayjs.unix(time.value).format("mm分ss秒");
    resume()
  }

  return {start,timeText}
}